<template>
  <div class="login-view">
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <van-cell-group>
      <van-field
        v-model="phone"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <van-field
        v-model="password"
        type="password"
        label="密码"
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>

    <van-button type="primary" block @click="login">立即登录</van-button>

    <div style="height: 15px"></div>

    <van-row justify="space-between">
      <van-button
        plain
        type="primary"
        size="small"
        :class="{ 'button-hover': hoverForgot }"
        @mouseenter="hoverForgot = true"
        @mouseleave="hoverForgot = false"
        @click="forgotPassword"
      >
        忘记密码？
      </van-button>
      <van-button
        plain
        size="small"
        type="primary"
        to="/register"
        :class="{ 'button-hover': hoverRegister }"
        @mouseenter="hoverRegister = true"
        @mouseleave="hoverRegister = false"
      >
        未注册账号?
      </van-button>
    </van-row>
    <div class="login-footer">
      <van-checkbox v-model="agree">
        未注册手机号登录后将自动生成账号，且代表你已阅读并同意
        <a href="#">《用户服务协议》</a>、
        <a href="#">《隐私政策》</a>
      </van-checkbox>
    </div>
  </div>
</template>

<script setup>
//依赖导入区
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Base64 } from "js-base64";
import http from "../../utils/http";
import { showNotify } from "vant";
//变量区:
//1.创建路由实例
const router = useRouter(); // 正确地获取路由器实例
//2.手机号码
const phone = ref("");
//3.密码
const password = ref("");
//4.同意协议
const agree = ref(false);
//5.路由重定向的参数
const redirect = router.currentRoute.value.query.redirect; // 获取重定向参数
//6.鼠标是否悬浮在忘记密码的按钮上
const hoverForgot = ref(false);
//7.鼠标是否悬浮在注册的按钮上
const hoverRegister = ref(false);
// console.log("重定向的参数为", redirect);
//方法区:
//1.登录按钮被点击事件
const login = async () => {
  try {
    console.log("登陆按钮被点击");

    if (!phone.value) {
      showNotify({
        type: "danger",
        message: "手机号码不能为空",
        duration: 1000,
      });
      return;
    } else if (!password.value) {
      showNotify({ type: "danger", message: "密码不能为空", duration: 1000 });

      return;
    } else if (!agree.value) {
      showNotify({
        type: "danger",
        message: "请同意用户协议和隐私政策",
        duration: 1000,
      });

      return;
    } else {
      console.log("执行登录逻辑");
      //发送登录请求
      const jwt = await sendLoginRequest();
      if (jwt === null || jwt === "") {
        showNotify({
          type: "danger",
          message: "账号或密码错误",
          duration: 1000,
        });
      } else {
        // 成功的消息通知
        showNotify({ type: "success", message: "登录成功!", duration: 1000 });
        // 等待通知展示完成
        await new Promise((resolve) => setTimeout(resolve, 1000)); // 等待1000毫秒
        // 登录成功后，如果存在重定向参数，则重定向到该路径
        if (redirect) {
          // console.log("正在重定向", redirect);
          router.push(redirect);
        } else {
          // 如果没有重定向参数，则重定向到默认页面:首页
          router.push("/");
        }
      }
    }
  } catch (error) {
    console.error("登录过程中发生错误：", error);
  }
};
//2.忘记密码被点击事件
const forgotPassword = () => {
  showNotify({ type: "primary", message: "该功能暂未实现", duration: 1000 });
};
//3.返回按钮被点击事件
const onClickLeft = () => {
  router.push("/first");
};
//4.发送登录请求
const sendLoginRequest = async () => {
  // console.log("商铺分类的函数被执行");
  try {
    const response = await http.get("/user/login", {
      params: {
        username: phone.value,
        password: password.value,
      },
    });
    const jwt = response.data.data;
    //返回空的情况
    if (jwt === null || jwt === "") return null;
    // 将 jwt 令牌以 token:value(jwt) 的形式存放于 localStorage
    localStorage.setItem("token", jwt);
    //解析jwt令牌并将userId存入本地:
    parseJwt(jwt);
    //返回值为jwt
    return jwt;
  } catch (error) {
    console.error(error);
  }
};

//5.解析jet令牌
const parseJwt = (jwt) => {
  // JWT令牌分为三部分，用点（.）分隔：Header.Payload.Signature
  const base64Payload = jwt.split(".")[1]; // 获取Payload部分

  // 使用js-base64解码Base64编码的Payload
  const payload = Base64.atob(base64Payload);

  // 将解码后的字符串转换为JSON对象
  const parsedPayload = JSON.parse(payload);

  // 从载荷中提取userId
  const userId = parsedPayload.userId;
  // 将userId存储在localStorage中
  localStorage.setItem("userId", userId);
  // console.log("得到用户id为");
  // console.log(userId);
};
</script>

<style scoped>
::v-deep(.van-nav-bar) {
  background-color: white;
}
.login-view {
  padding: 20px;
}

.login-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.login-footer .van-button {
  font-size: 14px;
}
/* 你可以在这里定义按钮的悬浮样式 */
.button-hover {
  background-color: #7e7b8362; /* 悬浮时的背景颜色 */
  color: rgb(44, 31, 31); /* 悬浮时的文字颜色 */
}
</style>